<html>
<head>
<link rel="shortcut icon" href="./favicon.ico">
<link rel="stylesheet" type="text/css" href="./style.css">
<link rel="canonical" href="./Gray_to_Binary_Reflected.html">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="*(This code was contributed by Jeff Cassidy at Isophase Computing (<jeff@isophase-computing.ca>, <https://github.com/isophase>), with edits by myself.)*">
<title>Gray to Binary Reflected</title>
</head>
<body>

<p class="inline bordered"><b><a href="./Gray_to_Binary_Reflected.v">Source</a></b></p>
<p class="inline bordered"><b><a href="./legal.html">License</a></b></p>
<p class="inline bordered"><b><a href="./index.html">Index</a></b></p>

<h1>Gray to Binary (Reflected Binary)</h1>
<p><em>(This code was contributed by Jeff Cassidy at Isophase Computing
 (<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#106;&#101;&#102;&#102;&#64;&#105;&#115;&#111;&#112;&#104;&#97;&#115;&#101;&#45;&#99;&#111;&#109;&#112;&#117;&#116;&#105;&#110;&#103;&#46;&#99;&#97;">&#106;&#101;&#102;&#102;&#64;&#105;&#115;&#111;&#112;&#104;&#97;&#115;&#101;&#45;&#99;&#111;&#109;&#112;&#117;&#116;&#105;&#110;&#103;&#46;&#99;&#97;</a>, <a href="https://github.com/isophase">https://github.com/isophase</a>), with edits
 by myself.)</em></p>
<p>Converts a Reflected Binary <a href="https://en.wikipedia.org/wiki/Gray_code">Gray
 Code</a> to the corresponding
 unsigned binary number. </p>
<p>Because of the abundance of binary adder/subtractor logic on an FPGA, if
 you want to do arithmetic with a Gray Code number, you are better off to
 first convert it to binary, do the math, then <a href="./Binary_to_Gray_Reflected.html">convert it back to Gray
 Code</a>.</p>

<pre>
`default_nettype none

module <a href="./Gray_to_Binary_Reflected.html">Gray_to_Binary_Reflected</a>
#(
    parameter WORD_WIDTH = 0
)
(
    input  wire [WORD_WIDTH-1:0] gray_in,
    output reg  [WORD_WIDTH-1:0] binary_out
);

    localparam ZERO = {WORD_WIDTH{1'b0}};

    initial begin
        binary_out = ZERO;
    end

    function [WORD_WIDTH-1:0] gray_to_binary
    (
        input [WORD_WIDTH-1:0] gray
    );
        integer i;
        reg [WORD_WIDTH-1:0] binary;

        begin
            binary[WORD_WIDTH-1] = gray[WORD_WIDTH-1];

            for(i=WORD_WIDTH-2; i >= 0; i=i-1) begin
                binary[i] = binary[i+1] ^ gray[i];
            end

            gray_to_binary = binary;
        end
    endfunction

    always@(*) begin
        binary_out = gray_to_binary(gray_in);
    end

endmodule
</pre>

<hr>
<p><a href="./index.html">Back to FPGA Design Elements</a>
<center><a href="https://fpgacpu.ca/">fpgacpu.ca</a></center>
</body>
</html>

